package algorithm.beforestart.primary.str;

import java.util.Arrays;

public class reverseInt {
    public static int reverse(int x) {

        boolean flag=true;
        if(x<0){
            flag=false;
            x=-x;
        }


        String str =x+"";
        char[] strchar =new char[str.length()];
        for(int i=0;i<str.length();i++){
            strchar[i] =str.charAt(i);
        }


        reverseString(strchar);

        String resultStr="";
        for(int i=0;i<strchar.length;i++){
            resultStr =resultStr+strchar[i];
        }

        try{
            int result =Integer.parseInt(resultStr);
            if(!flag){
                return  -result;
            }
            return  result;
        }catch (Exception e){
            return 0;
        }
    }

    public static void reverseString(char[] s) {
        int n=s.length;
        int left =0;int right=n-1;
        while (right>=left){
            swap(s,left,right);
            left++;
            right--;
        }
    }

    private static void swap(char[] s, int left, int right) {
        Character temp =s[left];
        s[left] =s[right];
        s[right]=temp;
    }

    public static int reverse2(int x) {
        long res = 0;
        while (x != 0) {
            res = res * 10 + x % 10;
            x /= 10;
        }
        return (int) res == res ? (int) res : 0;
    }



    public static void main(String[] args) {
        System.out.println(reverse2(123));
    }

}
